package com.learning.platform.controller;

import com.learning.platform.dto.ApiResponse;
import com.learning.platform.dto.CourseResponse;
import com.learning.platform.security.UserPrincipal;
import com.learning.platform.service.EnrollmentService;
import org.springframework.data.domain.Page;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/enrollments")
public class EnrollmentController {
    
    private final EnrollmentService enrollmentService;
    
    public EnrollmentController(EnrollmentService enrollmentService) {
        this.enrollmentService = enrollmentService;
    }
    
    /**
     * 选课
     */
    @PostMapping("/{courseId}")
    public ApiResponse<Void> enrollCourse(@PathVariable Long courseId, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        enrollmentService.enrollCourse(principal.getUserId(), courseId);
        return ApiResponse.success(null, "选课成功");
    }
    
    /**
     * 取消选课
     */
    @DeleteMapping("/{courseId}")
    public ApiResponse<Void> unenrollCourse(@PathVariable Long courseId, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        enrollmentService.unenrollCourse(principal.getUserId(), courseId);
        return ApiResponse.success(null, "取消选课成功");
    }
    
    /**
     * 检查是否已选课
     */
    @GetMapping("/{courseId}/status")
    public ApiResponse<Boolean> checkEnrollmentStatus(@PathVariable Long courseId, Authentication auth) {
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        boolean enrolled = enrollmentService.isEnrolled(principal.getUserId(), courseId);
        return ApiResponse.success(enrolled);
    }
    
    /**
     * 获取我的选课列表
     */
    @GetMapping("/my")
    public ApiResponse<Page<CourseResponse>> getMyEnrollments(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            Authentication auth) {
        
        UserPrincipal principal = (UserPrincipal) auth.getPrincipal();
        Page<CourseResponse> courses = enrollmentService.getUserEnrolledCourses(
            principal.getUserId(), page, pageSize);
        return ApiResponse.success(courses);
    }
}


